<template>
  <el-select
    v-model="value"
    :disabled="disabled"
    :size="size"
    :multiple="multiple"
    :filterable="filterable"
    :clearable="clearable"
    :collapse-tags="collapseTags"
    style="width: 100%;"
    @change="handleChange"
    :placeholder="plzSelect?$t('message.plzSelect'):(labelAll?labelAll:$t('common.text.all'))"
    :popper-class="{'edu-dict-select': showBar}"
  >
    <el-row class="select-tool-bar" v-if="showBar">
      <el-col :span="12">
        <el-button size="mini" @click="checkAll" style="width: 100%;">{{$t('common.btn.checkAll')}}</el-button>
      </el-col>
      <el-col :span="12">
        <el-button size="mini" @click="cancelAll" style="width: 100%;">{{$t('common.btn.cancelAll')}}</el-button>
      </el-col>
    </el-row>
    <el-option :label="$t('common.text.all')" value="" v-if="showAll"/>
    <el-option v-for="item in dataList" :key="item.value" :label="item.label" :value="item.value"></el-option>
  </el-select>
</template>
<script>

import UTILS from "common/src/utils/utils";
import { queryDic } from "common/src/api/dictionary";
/**
 * 专业字典下拉框组件
 */
export default {
  name: "EduMajorSelect",
  props: {
    value: {
      required: true
    },
    disabled: {
      type: Boolean,
      default: false
    },
    multiple: {
      type: Boolean,
      default: false
    },
    filterable: {
      type: Boolean,
      default: false
    },
    size: {
      type: String,
      default: ''
    },
    clearable: {
      type: Boolean,
      default: true
    },
    collapseTags:{
      default: true
    },
    plzSelect: { // 用于展示placeholder的默认值 而不是 “全部”
      type: Boolean,
      default: false
    },
    labelAll: {
      type: String
    },
    showAll: {
      type: Boolean,
      default: false
    },
    ///// 影响专业要素 start /////
    faculty:{
      default: ''
    },
    grade:{
      default: ''  // 本科生专用（年级）
    },
    degreeType:{
      default: ''  // 研究生专用（学位类型）
    },
    ///// 影响专业要素 end /////
    showToolBar: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      projectId: this.$store.getters.getProjectId(),
      dataList:[]
    }
  },
  watch:{
    faculty: {
      handler: function(newVal, oldVal) {
        this.query();
      },
      immediate: false,    // 必填项，第一次可以不触发
    },
    grade: {
      handler: function(newVal, oldVal) {
        if(this.projectId != 1) {
          return;
        }
        this.query();
      },
      immediate: true,
    },
    degreeType: {
      handler: function(newVal, oldVal) {
        if(this.projectId == 1) {
          return;
        }
        this.query();
      },
      immediate: true,
    },
  },
  computed:{
    showBar(){
      return this.multiple && this.showToolBar;
    }
  },
  mounted() {
  },
  created() {
    if (this.multiple && !Array.isArray(this.value)) {
      this.$emit("input", []);
    }
    if (!this.multiple && Array.isArray(this.value)) {
      this.$emit("input", "");
    }
  },
  methods: {
    handleChange(val){
      this.$emit("input", val);
      this.$emit('change', val);
    },
    query(){
      // 1. 必须有学院
      if(!this.faculty || this.faculty.length < 1) {
        this.handleChange(this.multiple ? [] : '');
        this.dataList = [];
        return;
      }

      let filter = {'facultys': this.faculty };
      if(this.projectId == 1) {
        // 2.1 必须有年级
        if(!this.grade || this.grade.length < 1) {
          this.handleChange(this.multiple ? [] : '');
          this.dataList = [];
          return;
        }
        filter.grade = this.grade[0];
      } else {
        // 2.2 必须有学位类型
        if(!this.degreeType || this.degreeType.length < 1) {
          this.handleChange(this.multiple ? [] : '');
          this.dataList = [];
          return;
        }
        filter.degreeType = this.degreeType;
      }
      let params = {
        lang: this.$store.getters.language || "cn",
        type: "allChild",
        keys: ["G_ZY"],
        filter: filter
      };
      queryDic(params).then(res => {
        let newValue = [];
        this.dataList = [];
        for (let key in res.data.G_ZY) {
          this.dataList.push({
            value: key,
            label: String(res.data.G_ZY[key])
          });
          if(this.multiple && this.multiple == true) {
            if(this.value.includes(key)) {
              newValue.push(key);
            }
          } else {
            if(this.value == key) {
              newValue.push(key);
            }
          }
        }
        this.value = this.multiple ? newValue : newValue.join(",");
        this.handleChange(this.value);
        this.$emit('load-done', this.dataList);
      });
    },
    checkAll(){
      const val = [];
      _.forEach(this.dataList, (d)=>{
        val.push(d.value);
      });
      this.handleChange(val);
    },
    cancelAll(){
      this.handleChange([]);
    }
  }
};

</script>

<style scoped>
</style>
